<template>
  <div class="report-chat-container">
    <!-- 左侧会话列表 -->
    <div class="chat-sidebar">
      <ReportChatSessionList
        ref="sessionListRef"
        :selected-session-id="selectedSessionId"
        @session-select="handleSessionSelect"
        @create-new="handleCreateNew"
        @session-updated="handleSessionUpdated"
      />
    </div>

    <!-- 右侧聊天区域 -->
    <div class="chat-main">
      <transition name="slide-fade" mode="out-in">
        <!-- 聊天界面 -->
        <div v-if="selectedSessionId || isNewChat" class="chat-content">
          <div class="chat-header">
            <div class="header-info">
              <span v-if="currentSession">{{ currentSession.title }}</span>
              <span v-else>新建对话</span>
            </div>
          </div>

          <!-- 消息列表 -->
          <div class="message-list" ref="messageListRef">
            <div
              v-for="message in messages"
              :key="message.id"
              class="message-item"
              :class="{ 'is-user': message.role === 'user' }"
            >
              <div class="message-avatar">
                <img
                  :src="message.role === 'user' ? userAvatar : agentAvatar"
                  alt="avatar"
                />
              </div>
              <div class="message-content">
                <!-- 思考内容 -->
                <div v-if="message.thinkingContent" class="thinking-content">
                  <div class="thinking-header">
                    <span>深度思考中...</span>
                  </div>
                  <div class="thinking-text">{{ message.thinkingContent }}</div>
                </div>
                <!-- 消息内容 -->
                <div class="message-text" v-html="formatMessage(message.content)"></div>
                <!-- 附件 -->
                <div v-if="message.files" class="message-files">
                  <div
                    v-for="file in parseFiles(message.files)"
                    :key="file.fileName"
                    class="file-item"
                  >
                    <span>{{ file.fileName }}</span>
                  </div>
                </div>
              </div>
            </div>

            <!-- 加载状态 -->
            <div v-if="isStreaming" class="message-item">
              <div class="message-avatar">
                <img :src="agentAvatar" alt="avatar" />
              </div>
              <div class="message-content">
                <div class="loading-dots">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>

          <!-- 输入区域 -->
          <div class="chat-input">
            <div class="input-tools">
              <el-button
                type="text"
                :class="{ active: isDeepThinking }"
                @click="isDeepThinking = !isDeepThinking"
                size="small"
              >
                <el-icon><BrainFilled /></el-icon>
                深度思考
              </el-button>
              <el-upload
                ref="uploadRef"
                :show-file-list="false"
                :before-upload="handleFileSelect"
                multiple
                accept=".docx,.doc,.ppt,.txt,.pdf,.xls,.xlsx,.xlsm"
              >
                <el-button type="text" size="small">
                  <el-icon><Paperclip /></el-icon>
                  附件
                </el-button>
              </el-upload>
            </div>

            <!-- 已选择的文件 -->
            <div v-if="selectedFiles.length > 0" class="selected-files">
              <div
                v-for="(file, index) in selectedFiles"
                :key="index"
                class="file-tag"
              >
                <span>{{ file.name }}</span>
                <el-icon @click="removeFile(index)"><Close /></el-icon>
              </div>
            </div>

            <div class="input-area">
              <el-input
                v-model="inputMessage"
                type="textarea"
                :rows="3"
                placeholder="我可以帮你处理各类文档的工作，例如内容提炼、AI润色、文档对比等，请把你的任务交给我吧~"
                @keydown.ctrl.enter="handleSendMessage"
              />
              <el-button
                type="primary"
                :disabled="!inputMessage.trim() && selectedFiles.length === 0"
                :loading="isStreaming"
                @click="handleSendMessage"
                class="send-btn"
              >
                <el-icon><Top /></el-icon>
              </el-button>
            </div>
          </div>
        </div>

        <!-- 欢迎界面 -->
        <div v-else class="welcome-screen">
          <div class="welcome-content">
            <div class="welcome-title">
              <img src="@/assets/images/logo.png" alt="logo" class="logo" />
              <h2>我是智能报告系统，很高兴见到你！</h2>
            </div>
            <div class="welcome-description">
              <p>我可以帮你处理各类文档的工作，例如内容提炼、AI润色、文档对比等</p>
            </div>
          </div>
        </div>
      </transition>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { BrainFilled, Paperclip, Close, Top } from '@element-plus/icons-vue';
import type { ChatSessionVo, ChatMessageDetailVo } from '@/api/chat/types';
import { useFetchStream } from '@/hooks/useFetchStream';
import { useChatStore } from '@/stores/modules/chat';
import { useUserStore } from '@/stores/modules/user';
import ReportChatSessionList from '@/components/ReportChatSessionList/index.vue';
import agentAvatar from '@/assets/images/logo.png';
import userAvatar from '@/assets/images/user.png';

const chatStore = useChatStore();
const userStore = useUserStore();

// 组件引用
const sessionListRef = ref();
const messageListRef = ref();
const uploadRef = ref();

// 状态管理
const selectedSessionId = ref<number | null>(null);
const currentSession = ref<ChatSessionVo | null>(null);
const isNewChat = ref(false);
const messages = ref<ChatMessageDetailVo[]>([]);
const inputMessage = ref('');
const selectedFiles = ref<File[]>([]);
const isDeepThinking = ref(false);
const isStreaming = ref(false);

// 流式请求Hook
const {
  isThinking,
  isAnswering,
  isLoading,
  thinkingBuffer,
  answeringBuffer,
  conversationId,
  fetchData,
  abort
} = useFetchStream({
  url: '/api/intelligent', // 根据实际接口调整
  onThinking: (content: string) => {
    // 更新思考内容
    if (messages.value.length > 0) {
      const lastMessage = messages.value[messages.value.length - 1];
      if (lastMessage.role !== 'user') {
        lastMessage.thinkingContent = content;
      }
    }
  },
  onAnswering: (content: string) => {
    // 更新回答内容
    if (messages.value.length > 0) {
      const lastMessage = messages.value[messages.value.length - 1];
      if (lastMessage.role !== 'user') {
        lastMessage.content = content;
      }
    }
    scrollToBottom();
  },
  onComplete: () => {
    isStreaming.value = false;
    // 刷新会话列表
    sessionListRef.value?.refresh();
  },
  onError: (error: any) => {
    isStreaming.value = false;
    ElMessage.error('发送消息失败: ' + error.message);
  }
});

// 处理会话选择
const handleSessionSelect = async (session: ChatSessionVo) => {
  selectedSessionId.value = session.id;
  currentSession.value = session;
  isNewChat.value = false;
  
  // 加载会话消息
  await loadSessionMessages(session.id);
};

// 处理新建对话
const handleCreateNew = () => {
  selectedSessionId.value = null;
  currentSession.value = null;
  isNewChat.value = true;
  messages.value = [];
  inputMessage.value = '';
  selectedFiles.value = [];
};

// 处理会话更新
const handleSessionUpdated = () => {
  // 如果当前选中的会话被删除，回到欢迎界面
  if (selectedSessionId.value && !chatStore.sessionList.find(s => s.id === selectedSessionId.value)) {
    handleCreateNew();
  }
};

// 加载会话消息
const loadSessionMessages = async (sessionId: number) => {
  try {
    const messageList = await chatStore.requestSessionMessages(sessionId);
    messages.value = messageList.sort((a, b) => a.messageId - b.messageId);
    nextTick(() => {
      scrollToBottom();
    });
  } catch (error) {
    console.error('加载会话消息失败:', error);
    ElMessage.error('加载会话消息失败');
  }
};

// 处理文件选择
const handleFileSelect = (file: File) => {
  selectedFiles.value.push(file);
  return false; // 阻止自动上传
};

// 移除文件
const removeFile = (index: number) => {
  selectedFiles.value.splice(index, 1);
};

// 发送消息
const handleSendMessage = async () => {
  if (!inputMessage.value.trim() && selectedFiles.value.length === 0) {
    return;
  }

  const userMessage: ChatMessageDetailVo = {
    id: Date.now(),
    messageId: Date.now(),
    agent: '用户',
    content: inputMessage.value,
    role: 'user',
    sesssionId: selectedSessionId.value || 0,
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString(),
    creator: userStore.userInfo?.userId || 0,
    updater: userStore.userInfo?.userId || 0,
    thinkingEnabled: isDeepThinking.value ? 1 : 0,
    files: selectedFiles.value.length > 0 ? JSON.stringify(selectedFiles.value.map(f => ({
      fileName: f.name,
      fileSize: f.size,
      fileType: f.type
    }))) : undefined
  };

  // 添加用户消息
  messages.value.push(userMessage);

  // 添加AI回复占位符
  const aiMessage: ChatMessageDetailVo = {
    id: Date.now() + 1,
    messageId: Date.now() + 1,
    agent: '智能助手',
    content: '',
    role: 'assistant',
    sesssionId: selectedSessionId.value || 0,
    createTime: new Date().toISOString(),
    updateTime: new Date().toISOString(),
    creator: 0,
    updater: 0,
    thinkingEnabled: isDeepThinking.value ? 1 : 0,
    thinkingContent: ''
  };

  messages.value.push(aiMessage);
  
  // 准备请求数据
  const requestData = {
    queryStr: inputMessage.value,
    query: inputMessage.value,
    name: '智能助手',
    agent: '智能助手',
    isDeepThinking: isDeepThinking.value,
    files: selectedFiles.value.map(f => ({
      fileName: f.name,
      fileSize: f.size,
      fileType: f.type,
      file: f
    }))
  };

  // 清空输入
  const currentInput = inputMessage.value;
  inputMessage.value = '';
  selectedFiles.value = [];
  isStreaming.value = true;

  // 滚动到底部
  nextTick(() => {
    scrollToBottom();
  });

  try {
    // 发送流式请求
    await fetchData(requestData);
    
    // 如果是新对话，更新会话ID
    if (isNewChat.value && conversationId.value) {
      selectedSessionId.value = conversationId.value;
      isNewChat.value = false;
    }
  } catch (error) {
    console.error('发送消息失败:', error);
    // 移除AI回复占位符
    messages.value.pop();
  }
};

// 滚动到底部
const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
  }
};

// 格式化消息内容
const formatMessage = (content: string) => {
  // 简单的换行处理，可以根据需要扩展为Markdown渲染
  return content.replace(/\n/g, '<br>');
};

// 解析文件信息
const parseFiles = (filesStr: string) => {
  try {
    return JSON.parse(filesStr);
  } catch {
    return [];
  }
};

// 组件挂载
onMounted(() => {
  // 默认显示欢迎界面
  handleCreateNew();
});
</script>

<style scoped lang="scss">
.report-chat-container {
  display: flex;
  height: 100vh;
  background: #f5f5f5;
}
.chat-sidebar {
  width: 280px;
  background: #ffffff;
  border-right: 1px solid #e0e0e0;
}
.chat-main {
  display: flex;
  flex: 1;
  flex-direction: column;
  background: #ffffff;
}
.chat-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.chat-header {
  padding: 16px 24px;
  background: #ffffff;
  border-bottom: 1px solid #e0e0e0;
  .header-info {
    font-size: 16px;
    font-weight: 500;
    color: #333333;
  }
}
.message-list {
  flex: 1;
  padding: 16px 24px;
  overflow-y: auto;
  .message-item {
    display: flex;
    margin-bottom: 24px;
    &.is-user {
      flex-direction: row-reverse;
      .message-content {
        margin-right: 12px;
        margin-left: 0;
        color: #ffffff;
        background: #409eff;
      }
    }
    .message-avatar {
      flex-shrink: 0;
      width: 32px;
      height: 32px;
      overflow: hidden;
      border-radius: 50%;
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    .message-content {
      max-width: 70%;
      padding: 12px 16px;
      margin-left: 12px;
      background: #f0f0f0;
      border-radius: 12px;
      .thinking-content {
        padding: 8px 12px;
        margin-bottom: 12px;
        background: rgb(64 158 255 / 10%);
        border-left: 3px solid #409eff;
        border-radius: 8px;
        .thinking-header {
          margin-bottom: 4px;
          font-size: 12px;
          color: #409eff;
        }
        .thinking-text {
          font-size: 14px;
          line-height: 1.4;
          color: #666666;
        }
      }
      .message-text {
        font-size: 14px;
        line-height: 1.6;
        word-wrap: break-word;
      }
      .message-files {
        margin-top: 8px;
        .file-item {
          display: inline-block;
          padding: 4px 8px;
          margin-right: 8px;
          margin-bottom: 4px;
          font-size: 12px;
          background: rgb(0 0 0 / 10%);
          border-radius: 4px;
        }
      }
    }
  }
  .loading-dots {
    display: flex;
    gap: 4px;
    span {
      width: 6px;
      height: 6px;
      background: #cccccc;
      border-radius: 50%;
      animation: loading 1.4s infinite ease-in-out;
      &:nth-child(1) { animation-delay: -0.32s; }
      &:nth-child(2) { animation-delay: -0.16s; }
    }
  }
}

@keyframes loading {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}
.chat-input {
  padding: 16px 24px;
  background: #ffffff;
  border-top: 1px solid #e0e0e0;
  .input-tools {
    display: flex;
    gap: 12px;
    margin-bottom: 12px;
    .el-button {
      padding: 4px 8px;
      font-size: 12px;
      &.active {
        color: #409eff;
        background: rgb(64 158 255 / 10%);
      }
    }
  }
  .selected-files {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 12px;
    .file-tag {
      display: flex;
      gap: 4px;
      align-items: center;
      padding: 4px 8px;
      font-size: 12px;
      background: #f0f0f0;
      border-radius: 4px;
      .el-icon {
        color: #999999;
        cursor: pointer;
        &:hover {
          color: #f56c6c;
        }
      }
    }
  }
  .input-area {
    display: flex;
    gap: 12px;
    align-items: flex-end;
    .el-textarea {
      flex: 1;
    }
    .send-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 40px;
      height: 40px;
      padding: 0;
      border-radius: 50%;
    }
  }
}
.welcome-screen {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  .welcome-content {
    text-align: center;
    .welcome-title {
      display: flex;
      gap: 12px;
      align-items: center;
      justify-content: center;
      margin-bottom: 16px;
      .logo {
        width: 40px;
        height: 40px;
      }
      h2 {
        margin: 0;
        font-size: 24px;
        color: #333333;
      }
    }
    .welcome-description {
      font-size: 16px;
      color: #666666;
    }
  }
}

// 过渡动画
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease;
}
.slide-fade-enter-from,
.slide-fade-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

// 滚动条样式
.message-list::-webkit-scrollbar {
  width: 6px;
}
.message-list::-webkit-scrollbar-track {
  background: #f1f1f1;
}
.message-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}
.message-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>